# encoding=utf-8
import jieba
import wordcloud
import imageio
import matplotlib.pyplot as plt

def generate_word_cloud(text, image_path, output_path):
    # 读取背景图片
    image = imageio.imread(image_path)

    # 使用 jieba 进行中文分词
    words = jieba.cut(text, cut_all=False)

    # 将分词结果转换为字符串
    words_str = " ".join(words)

    # 创建词云对象
    wc = wordcloud.WordCloud(
        background_color="white",
        mask=image,
        contour_width=1,
        contour_color="steelblue",
        font_path='C:/Windows/Fonts/msyh.ttc'
    )

    # 生成词云
    wc.generate(words_str)

    # 显示词云
    plt.imshow(wc, interpolation="bilinear")
    # plt.axis("off")
    # plt.show()

    # 保存词云图片
    wc.to_file(output_path)

# 示例文本
text = "这是一个示例文本，用于生成词云。词云是一种可视化技术，用于展示文本数据中的关键词。"

# 输入背景图路径
image_path = "image-pkq.jpg"

# 输入待解析文件路径
file_path = "snowtime.txt"

# 读取待解析文件
with open(file_path, "r", encoding="ANSI") as f:
    text = f.read()

# 输出词云图片路径
output_path = "image-29.jpg"

# 生成词云
generate_word_cloud(text, image_path, output_path)